import jwt
from django.http import JsonResponse
from django.conf import settings


# 登录状态验证
def authorization(func):
    def wrap(request, *args, **kwargs):

        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            return JsonResponse({"code": 403, "error": "Please login"})

        try:
            res = jwt.decode(token, settings.KEY, algorithms='HS256')
        except:
            return JsonResponse({"code": 403, "error": "Please login"})

        from user.models import UserProfile
        username = res['username']
        user = UserProfile.objects.get(username=username)
        request.user = user  # 已登录用户

        return func(request,*args, **kwargs)

    return wrap

__all__ = ['authorization']